<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { type ECharts, graphic, init } from 'echarts'
import type { Seller } from '@/types/eCommerce'

const props = defineProps<{
  sellerData: Seller[]
}>()
const echarts_ref = ref<HTMLDivElement>()
let myECharts: ECharts
//初始化
const initEcharts = () => {
  // 初始化配置项
  const initOption = {
    title: {
      text: '商家销售统计',
      top: '2%',
      left: '2%'
    },
    grid: {
      top: '12%',
      left: '10%',
      bottom: '6%',
      right: '10%',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'value',
      show: true,
      position: 'top',
      axisLine: {
        show: true
      },
      splitLine: {
        show: false
      }
    },
    yAxis: {
      show: true,
      type: 'category'
    },
    series: [{
      type: 'bar',
      label: {
        show: true,
        color: '#656565',
        position: 'right'
      },
      itemStyle: {
        color: new graphic.LinearGradient(0, 0, 1, 0, [
          {
            offset: 0,
            color: 'rgba(80,82,238,0.99)'
          }, {
            offset: 1,
            color: 'rgba(171,110,229,0.97)'
          }
        ])
      }
    }]
  }
  myECharts = init(echarts_ref.value as HTMLDivElement)
  myECharts.setOption(initOption, true)
}

const dataEcharts = () => {
  const series: number[] = []
  const yAxis: string[] = []
  props.sellerData.forEach(item => {
    series.unshift(item.value)
    yAxis.unshift(item.name)
  })
  const dataOption = {
    yAxis: {
      data: yAxis,
      max: 4,
      inverse: true
    },
    series: [{
      data: series
    }]
  }
  myECharts.setOption(dataOption)
}


// 动态适配
const adapterEcharts = () => {
  const width = echarts_ref.value!.offsetWidth
  const adapterOption = {
    title: {
      textStyle: {
        fontSize: width / 100 * 3
      }
    },
    series: [{
      barWidth: width / 100 * 5,
      itemStyle: {
        borderRadius: [0, width / 100 * 2.5, width / 100 * 2.5, 0]
      }
    }]
  }
  myECharts.setOption(adapterOption)
  myECharts.resize()
}

const loading = ref(true)
watch(props, () => {
  dataEcharts()
  setTimeout(() => {
    loading.value = false
  }, 300)
})

onMounted(async () => {
  initEcharts()
  adapterEcharts()
  window.addEventListener('resize', adapterEcharts)
})


onUnmounted(() => {
  window.removeEventListener('resize', adapterEcharts)
})
</script>
<template>
  <div v-loading="loading" class="echarts">
    <div ref="echarts_ref" class="echartsDom"></div>
  </div>
</template>


<style scoped>
@import "@/assets/style/componentsEcharts.css";
</style>
